package com.itheima.utildemo;

import java.util.Random;
import java.util.concurrent.Semaphore;

public class Demo01 {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(10);
        for (int i = 0; i < 20; i++) {
            Thread t = new Thread(new Car(semaphore));
            t.setName("车辆"+i);
            t.start();
        }
    }

}

class  Car implements Runnable{
    private Semaphore semaphore;

    public Car(Semaphore semaphore) {
        this.semaphore = semaphore;
    }

    @Override
    public void run() {
        //想进停车场
        try {
            String name = Thread.currentThread().getName();
            System.out.println(name+"来到了门口准备停车");
            semaphore.acquire();
            System.out.println(name+"开进去了");
            // 停一会
            int time = new Random().nextInt(10) + 1;
            Thread.sleep(time);
            System.out.println(name+"停了"+time+"毫秒");
            // 离开
            semaphore.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }




    }
}
